package com.kh.statistics.video.core.login;

import com.kh.statistics.video.entity.VideoAccountsLogin;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class CookieConvertMyCookie {

    public static MyCookie CookieToMyCookie(Cookie cookie) {
        if (cookie == null) {
            return null;
        }
        MyCookie myCookie = new MyCookie();
        myCookie.setPath(cookie.getPath());
        myCookie.setName(cookie.getName());
        myCookie.setValue(cookie.getValue());
        myCookie.setDomain(cookie.getDomain());
        myCookie.setExpiry(cookie.getExpiry());
        myCookie.setHttpOnly(cookie.isHttpOnly());
        myCookie.setSecure(cookie.isSecure());
        return myCookie;
    }

    public static Set<MyCookie> CookiesToMyCookies(Set<Cookie> cookieList) {
        if (CollectionUtils.isEmpty(cookieList)) {
            return new HashSet<>();
        }
        return cookieList.stream().map(CookieConvertMyCookie::CookieToMyCookie).collect(Collectors.toSet());
    }

    public static void setCookies(WebDriver driver, VideoAccountsLogin videoAccountsLogin) {
        RemoteWebDriver remoteWebDriver = (RemoteWebDriver) driver;
        Object o = remoteWebDriver.executeScript("return document.cookie");
        if (Objects.isNull(o)) {
            return;
        }
        videoAccountsLogin.setCookies(String.valueOf(o));
    }
}
